package com.ja.openchat.ui.chat.adapter.viewholder;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.ja.openchat.R;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.model.message.MessageContent;
import com.zy.openchat.core.model.message.UiMessage;
import com.zy.openchat.core.model.photo.ThumbnailInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.ja.openchat.ui.chat.ConversationFragment;
import com.ja.openchat.ui.chat.annotation.EnableContextMenu;
import com.ja.openchat.ui.chat.annotation.MessageContentType;
import com.zy.openchat.Constants;
import com.zy.openchat.util.FileUtils;
import com.zy.openchat.util.TimeConvertUtils;
import com.zy.openchat.util.WeChatImageUtils;
import com.ja.openchat.views.BubbleImageView;
import com.ja.openchat.views.FullVideoView;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 小视频尺寸展示高仿微信,并且带上时间
 * 占位图-缩略图-原图
 */
@MessageContentType(TelegramManager.MessageType.MessageType_Video)
@EnableContextMenu
public class VideoMessageContentViewHolder extends MediaMessageContentViewHolder {
    private static final String TAG = "VideoMessageContentView";
    @BindView(R.id.imageView)
    public BubbleImageView imageView;
    @BindView(R.id.playImageView)
    public ImageView playImageView;
    @BindView(R.id.playerContaniner)
    public CardView playerContaniner;
    @BindView(R.id.time_tv)
    TextView time_tv;
    @BindView(R.id.videoView)
    public FullVideoView mVideoView;
    @BindView(R.id.video_info_view)
    View video_info_view;
    @BindView(R.id.video_duration_text)
    TextView video_duration_text;
    @BindView(R.id.video_download_text)
    TextView video_download_text;

    private String imagePath ;

    public VideoMessageContentViewHolder(ConversationFragment fragment, RecyclerView.Adapter adapter, View itemView) {
        super(fragment, adapter, itemView);
    }

    @Override
    public void onBind(UiMessage message, int position, int payloadType) {
        super.onBind(message, position, payloadType);
        MessageContent videoMessageContent =  message.message.content;
        if(videoMessageContent.video==null){
            return;
        }
        if(payloadType==100){
            if(videoMessageContent.video.isVideoDownloaded()){
                loadMedia(null,videoMessageContent.video.localVideoPath(),imageView);
            }
            resetVideoInfoView();
//            if(!videoMessageContent.video.isVideoDownloadComplete()){
//                TelegramManager.getTelegramManager().downloadFile(message.message.chat_id+"_" + message.message.id, message.message.getVideoFileId(), videoMessageContent.video.donwloadSize(), TelegramManager.FileType.FileType_Message_Video);
//            }
            return;
        }
        ThumbnailInfo thumbnail = null;
        if(videoMessageContent.video.thumbnail!=null&&videoMessageContent.video.thumbnail.isThumbnailDownloaded()){
            thumbnail = videoMessageContent.video.thumbnail;
        }

        int width = Constants.MEDIA_MAX_WIDTH;
        int height = Constants.MEDIA_MAX_WIDTH;
        if(message.message.getVideo()!=null){
            VideoInfo videoInfo = message.message.getVideo();
            int imageSize[] = WeChatImageUtils.getImageSizeByOrgSizeToWeChat((int)videoInfo.width, (int)videoInfo.height);
            width = imageSize[0]>0?imageSize[0]:Constants.MEDIA_MAX_WIDTH;
            height = imageSize[1]>0?imageSize[1]:Constants.MEDIA_MAX_WIDTH;
        }else if(thumbnail != null) {
            int imageSize[] = WeChatImageUtils.getImageSizeByOrgSizeToWeChat((int)thumbnail.width, (int)thumbnail.height);
            width = imageSize[0] > 0 ? imageSize[0] : Constants.MEDIA_MAX_WIDTH;
            height = imageSize[1] > 0 ? imageSize[1] : Constants.MEDIA_MAX_WIDTH;
        }
        imageView.getLayoutParams().width = width;
        imageView.getLayoutParams().height = height;
        playerContaniner.getLayoutParams().width = width;
        playerContaniner.getLayoutParams().height = height;

        time_tv.setText(TimeConvertUtils.formatLongTime(videoMessageContent.video.duration));
        if(videoMessageContent.video.isVideoDownloaded()){
            imagePath = videoMessageContent.video.localVideoPath();
            if(mVideoView.isPlaying()){
                playImageView.setVisibility(View.GONE);
            }else{
                playImageView.setVisibility(View.VISIBLE);
            }
        }else{
            imagePath = "";
            playImageView.setVisibility(View.VISIBLE);
        }
        if(!videoMessageContent.video.isVideoDownloadComplete()){
            TelegramManager.getTelegramManager().downloadFile(message.message.chat_id+"_" + message.message.id, message.message.getVideoFileId(), videoMessageContent.video.donwloadSize(), TelegramManager.FileType.FileType_Message_Video);
        }
        resetVideoInfoView();

        loadMedia(thumbnail!=null?thumbnail.file.local.path:null,imagePath,imageView);
        initVideoView(imagePath);
    }

    public void resetVideoInfoView(){
        MessageContent videoMessageContent =  message.message.content;
        if(videoMessageContent==null||videoMessageContent.video==null){
            return;
        }
        if(!videoMessageContent.video.isVideoDownloadComplete()){
            video_info_view.setVisibility(View.VISIBLE);
            video_duration_text.setText(TimeConvertUtils.formatLongTime(videoMessageContent.video.duration));
            video_download_text.setText(String.format("%s/%s", FileUtils.getReadableFileSize(videoMessageContent.video.donwloadSize()),FileUtils.getReadableFileSize(videoMessageContent.video.totalSize())));
        }else{
            video_info_view.setVisibility(View.GONE);
        }
    }


    public void loadVideoCover(){
        MessageContent videoMessageContent =  message.message.content;
        if(videoMessageContent.video==null){
            return;
        }
        resetVideoInfoView();
        if(videoMessageContent.video.isVideoDownloaded()) {
            imagePath = videoMessageContent.video.localVideoPath();
        }else{
            imagePath = "";
        }
        loadMedia(null,imagePath,imageView);
    }

    public void pausePlayVideo(){
        resetVideoInfoView();
        if(message.message!=null&&message.message.getVideo()!=null&&message.message.getVideo().isVideoDownloaded()){
            int position = mVideoView.getCurrentPosition();
            playerContaniner.setVisibility(View.VISIBLE);
            if(!mVideoView.isPlaying()&&position>0){
                mVideoView.start();
                mVideoView.seekTo(position);
                if(mVideoView.getDuration()<=position){
                    playImageView.setVisibility(View.VISIBLE);
                }else{
                    playImageView.setVisibility(View.GONE);
                }
            }else if(mVideoView.isPlaying()){
                playImageView.setVisibility(View.GONE);
            }else if(mVideoView.getTag(R.id.cacheControllerKey)==null){
                playImageView.setVisibility(View.GONE);
                mVideoView.setTag(R.id.cacheControllerKey,message.message.getVideo().localVideoPath());
                mVideoView.setVideoPath(message.message.getVideo().localVideoPath());
                mVideoView.start();
            }else{
                playImageView.setVisibility(View.GONE);
                mVideoView.start();
            }
        }else{
            playerContaniner.setVisibility(View.GONE);
            playImageView.setVisibility(View.VISIBLE);
        }

    }




    public void playVideo(){
        resetVideoInfoView();
        if(message.message!=null&&message.message.getVideo()!=null&&message.message.getVideo().isVideoDownloaded()){
            playerContaniner.setVisibility(View.VISIBLE);
            playImageView.setVisibility(View.GONE);
            mVideoView.setVideoPath(message.message.getVideo().localVideoPath());
            mVideoView.start();
        }else {
            playerContaniner.setVisibility(View.GONE);
            playImageView.setVisibility(View.VISIBLE);
        }

    }

    protected void initVideoView(String videoPath) {
        mVideoView.setOnErrorListener((mp, what, extra) -> {
            resetVideoView();
            return true;
        });
        mVideoView.setOnCompletionListener(mp -> {
            if(mp.getDuration() > mp.getCurrentPosition()){

            }else{
                resetVideoView();
            }

        });
        mVideoView.setOnPreparedListener(mediaPlayer -> {
            if(playImageView!=null&&mVideoView.isPlaying()){
                playImageView.setVisibility(View.GONE);
            }
            mediaPlayer.setVolume(0f, 0f);
        });
        if(!TextUtils.isEmpty(videoPath)){
            mVideoView.setVideoPath(videoPath);
        }

    }

    public void resetVideoView(){
        playImageView.setVisibility(View.VISIBLE);
        playerContaniner.setVisibility(View.GONE);
        mVideoView.stopPlayback();
    }

    @OnClick(R.id.videoContentLayout)
    void play() {
        previewMM();
    }

}
